package com.holly.unit.deform.api.factory;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.holly.unit.deform.api.enums.WidgetTypeEnum;
import com.holly.unit.deform.api.pojo.tool.DesformWidget;

import java.util.Arrays;
import java.util.Map;

/**
 * 类描述: 多选组件转换器
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/14 14:54
 */
public class MultipleConverter implements FieldCommentConverter{

    protected DesformWidget widget;

    public MultipleConverter(DesformWidget widget) {
        this.widget = widget;
    }

    @Override
    public Object converterToVal(String txt) {
        if (StrUtil.isNotBlank(txt)) {
            if (widget.getType() == WidgetTypeEnum.SELECT) {
                if (!widget.getOptions().isMultiple()) {
                    return txt;
                }
            }
            String[] arr = txt.split(delimiter);
            return new JSONArray(Arrays.asList(arr));
        }
        return txt;
    }

    @Override
    public Object converterToTxt(String val) {
        if (StrUtil.isNotBlank(val)) {
            if (widget.getType() == WidgetTypeEnum.SELECT) {
                if (!widget.getOptions().isMultiple()) {
                    return val;
                }
            }
            try {
                JSONArray jsonArray = JSON.parseArray(val);
                return String.join(delimiter, jsonArray.toJavaList(String.class));
            } catch (Exception e) {
                return val;
            }
        }
        return val;
    }

    @Override
    public Map<String, String> getConfig() {
        return null;
    }
}
